from tweets import TwitterStatuses, Tweet, User
from urllib2 import urlopen
from dateutil import parser
from datetime import date
import simplejson as json
import sys

def userfromdict(dict):
	u = User()
	u.FollowersCount = dict['followers_count']
	u.Description = dict['description']
	u.URL = dict['url']
	u.ProfileImage = dict['profile_image_url']
	u.Location = dict['location']
	u.ScreenName = dict['screen_name']
	u.Name = dict['name']
	return u

def tweetfromdict(dict):
	t = Tweet()
	t.Permalink = str(dict['id'])
	t.Content = dict['text']
	t.Truncated = dict['truncated']
	t.Source = dict['source']
	t.ReplyToUser = str(dict['in_reply_to_user_id'])
	t.ReplyToStatus = str(dict['in_reply_to_status_id'])
	t.Published = parser.parse(dict['created_at'])
	t.User = userfromdict(dict['user'])
	return t


def tweetsfromurl(url):
	statuses = json.loads(urlopen(url).read())
	return [tweetfromdict(s) for s in statuses]

if __name__ == '__main__':
	ts = TwitterStatuses(date.today().strftime("%d-%m-%Y" + ".tweets"),createnew=False)
	[ts.persist(t) for t in tweetsfromurl('http://twitter.com/statuses/public_timeline.json')]

	




